package com.pcbly.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.jdom.output.Format;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedOutput;
import org.jdom.Document;
import org.jdom.output.XMLOutputter;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Created by IntelliJ IDEA. User: irtgong Date: 2008-7-23 Time: 9:31:13 To
 * change this template use File | Settings | File Templates.
 */
public abstract class AbstractRss extends HttpServlet {

	/**
     *
     */
	private static final long serialVersionUID = -2551980824463396664L;

	private static final Log logger = LogFactory.getLog(AbstractRss.class);

	private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";

	// Initialize global variables
	public void init() throws ServletException {
	}

	public abstract SyndFeed getSyndFeed(WebApplicationContext wc)
			throws Exception;

	// Process the HTTP Get request
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType(CONTENT_TYPE);
		PrintWriter out = response.getWriter();

		WebApplicationContext wc = WebApplicationContextUtils
				.getWebApplicationContext(this.getServletContext());

		try {
			SyndFeed feed = getSyndFeed(wc);
			feed.setFeedType("rss_2.0");
			SyndFeedOutput output = new SyndFeedOutput();
			// String feedStr = output.outputString(feed);
			Document messagesDocument = output.outputJDom(feed);
			Format format = Format.getPrettyFormat();
			format.setOmitDeclaration(true);
			XMLOutputter xmlo = new XMLOutputter(format);
			xmlo.output(messagesDocument, out);
		} catch (Exception ex) {
			logger.error(ex);
		}
		out.close();
	}

	// Clean up resources
	public void destroy() {
	}
}
